<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElInput, ElButton, ElDialog } from 'element-plus'
import { postSendNow, getExpressCompanyList, getUserOtherOrders } from '@/api/goodsOderFrom'
import ExpressCompanySelector from '@/components/ExpressCompanySelector.vue'
import logger from '@/utils/logger'

const deliveryOrderData = ref(null)
const emit = defineEmits(['success-send'])
const props = defineProps({
  deliveryOrder: {
    type: Object,
    required: true,
  },
})

deliveryOrderData.value = props.deliveryOrder

const expressCompanycode = ref('')
const trackingNumber = ref('')
const expressCompanyname = ref('')
const selectorVisible = ref(false)

const expressCompanyList = ref([])
const expressCompanyLoading = ref(false)
let expressCompanyTimer = null

// 合并发货相关状态
const otherOrdersList = ref([])
const otherOrdersLoading = ref(false)
const mergedOrdersList = ref([]) // 已添加到发货单的订单列表

/**
 * @description 立即发货
 */
const handlePostSendNow = async () => {
  // 校验快递公司编码和快递单号必填
  if (!expressCompanycode.value) {
    ElMessage.error('快递公司编码不能为空')
    return
  }
  if (!trackingNumber.value) {
    ElMessage.error('快递单号不能为空')
    return
  }

  // 合并发货单数据，包含原订单和新添加的订单
  const allOrdersList = [...deliveryOrderData.value.pzOrderSendDList, ...mergedOrdersList.value]

  const payload = {
    ...deliveryOrderData.value,
    pzOrderSendDList: allOrdersList, // 包含合并的订单
    expressCompanycode: expressCompanycode.value,
    trackingNumber: trackingNumber.value,
  }

  try {
    const res = await postSendNow(payload)
    if (res.code === 200) {
      ElMessage.success(res.msg)
      emit('success-send')
    } else {
      ElMessage.error(res.msg || '发货失败')
    }
  } catch (error) {
    logger.error('发货失败:', error)
    ElMessage.error('发货失败')
  }
}

// 远程搜索快递公司，带防抖
const fetchExpressCompany = (queryString, cb) => {
  if (expressCompanyTimer) clearTimeout(expressCompanyTimer)
  expressCompanyTimer = setTimeout(async () => {
    if (!queryString) {
      expressCompanyList.value = []
      cb([])
      return
    }
    expressCompanyLoading.value = true
    try {
      const params = {
        queryFields: {
          expressCompanyname: queryString,
        },
        currentPage: 1,
        pageSize: 20,
      }
      const res = await getExpressCompanyList(params)
      if (res.success && res.data.list) {
        expressCompanyList.value = res.data.list
        cb(
          res.data.list.map((item) => ({
            value: item.expressCompanyname,
            code: item.expressCompanycode,
          })),
        )
      } else {
        expressCompanyList.value = []
        cb([])
      }
    } catch (err) {
      logger.error('获取快递公司失败:', err)
      expressCompanyList.value = []
      cb([])
    } finally {
      expressCompanyLoading.value = false
    }
  }, 300)
}

// 选择下拉项时，设置编码和名称
const handleSelectExpressCompanyAuto = (item) => {
  expressCompanycode.value = item.code
  expressCompanyname.value = item.value
}

const handleSelectExpressCompany = (row) => {
  expressCompanycode.value = row.expressCompanycode
  expressCompanyname.value = row.expressCompanyname
  selectorVisible.value = false
}

/**
 * @description 获取用户其他可合并的订单
 */
const fetchUserOtherOrders = async () => {
  if (!deliveryOrderData.value) return

  otherOrdersLoading.value = true
  try {
    // 构造过滤器，排除当前发货单中的订单和已合并的订单
    const allIncludedOrders = [
      ...(deliveryOrderData.value.pzOrderSendDList || []),
      ...mergedOrdersList.value,
    ]

    const memberOrderDIdList = allIncludedOrders.map((item) => ({
      memberOrderDId: item.memberOrderDId,
    }))

    const params = {
      memberAddressId: deliveryOrderData.value.memberAddressId || '', // 同一地址
      memberOrderDIdList: memberOrderDIdList, // 过滤已包含的订单
    }

    const res = await getUserOtherOrders(params)
    if (res.success && res.data) {
      otherOrdersList.value = res.data
    } else {
      otherOrdersList.value = []
    }
  } catch (err) {
    logger.error('获取其他订单失败:', err)
    otherOrdersList.value = []
    ElMessage.error('获取其他订单失败')
  } finally {
    otherOrdersLoading.value = false
  }
}

/**
 * @description 添加订单到发货单
 */
const handleAddOrder = async (row) => {
  // 检查是否已添加
  const isExist = mergedOrdersList.value.find((item) => item.memberOrderDId === row.memberOrderDId)
  if (isExist) {
    ElMessage.warning('该订单已添加到发货单中')
    return
  }

  // 添加到合并列表
  mergedOrdersList.value.push(row)
  ElMessage.success('订单添加成功')

  // 重新获取其他订单列表
  await fetchUserOtherOrders()
}

/**
 * @description 从发货单中移除订单
 */
const handleRemoveOrder = async (row) => {
  const index = mergedOrdersList.value.findIndex(
    (item) => item.memberOrderDId === row.memberOrderDId,
  )
  if (index > -1) {
    mergedOrdersList.value.splice(index, 1)
    ElMessage.success('订单移除成功')

    // 重新获取其他订单列表
    await fetchUserOtherOrders()
  }
}

// 组件挂载时获取其他订单
onMounted(() => {
  fetchUserOtherOrders()
})

onUnmounted(() => {
  if (expressCompanyTimer) {
    clearTimeout(expressCompanyTimer)
    expressCompanyTimer = null
  }
})
</script>

<template>
  <div class="delivery-note" v-if="deliveryOrderData">
    <h2 class="title">发货单</h2>
    <div class="order-info">
      <el-descriptions title="单据信息" :column="3" border>
        <el-descriptions-item label="发货单号">{{
          deliveryOrderData.sendNo || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{
          deliveryOrderData.sendTime || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="操作员">{{
          deliveryOrderData.dealerOperator || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="快递公司编码 *">
          <div style="display: flex; gap: 8px">
            <el-autocomplete
              v-model="expressCompanyname"
              :fetch-suggestions="fetchExpressCompany"
              placeholder="请输入快递公司名称"
              :loading="expressCompanyLoading"
              @select="handleSelectExpressCompanyAuto"
              clearable
              style="width: 300px"
            />
            <el-button @click="selectorVisible = true">选择</el-button>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="快递单号 *">
          <el-input v-model="trackingNumber" placeholder="请输入快递单号" />
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <el-dialog
      v-model="selectorVisible"
      align-center
      title="选择快递公司"
      width="80%"
      append-to-body
    >
      <ExpressCompanySelector @select="handleSelectExpressCompany" />
    </el-dialog>

    <div class="consignee-info">
      <el-descriptions title="收货信息" :column="2" border>
        <el-descriptions-item label="收货人">{{
          deliveryOrderData.consignee || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="行政区划">{{
          deliveryOrderData.xzqhName || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{
          deliveryOrderData.memberAddress || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          deliveryOrderData.mobilphone || '-'
        }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <div class="goods-list">
      <h3>商品列表</h3>
      <el-table :data="deliveryOrderData.pzOrderSendDList" border style="width: 100%">
        <el-table-column label="商品名称" min-width="180">
          <template #default="{ row }">
            {{ row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.goodsPicture"
              :preview-src-list="[scope.row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="商品类型" min-width="120">
          <template #default="{ row }">
            {{ row.dealerGoodsTypeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100">
          <template #default="{ row }">
            {{ row.specifications || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="采购数量" min-width="80">
          <template #default="{ row }">
            {{ row.purchaseQuantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" min-width="80">
          <template #default="{ row }">
            {{ row.unit || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品产地" min-width="150">
          <template #default="{ row }">
            {{ row.address || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品有效期" min-width="200">
          <template #default="scope">
            {{ scope.row.periodStartingDate || '-' }} - {{ scope.row.periodEndDate || '-' }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 已添加的合并订单列表 -->
    <div class="merged-goods-list" v-if="mergedOrdersList.length > 0">
      <h3>已添加的合并订单</h3>
      <el-table :data="mergedOrdersList" border style="width: 100%">
        <el-table-column label="商品名称" min-width="180">
          <template #default="{ row }">
            {{ row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.goodsPicture"
              :preview-src-list="[scope.row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="商品类型" min-width="120">
          <template #default="{ row }">
            {{ row.dealerGoodsTypeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100">
          <template #default="{ row }">
            {{ row.specifications || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="采购数量" min-width="80">
          <template #default="{ row }">
            {{ row.purchaseQuantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" min-width="80">
          <template #default="{ row }">
            {{ row.unit || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品产地" min-width="150">
          <template #default="{ row }">
            {{ row.address || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品有效期" min-width="200">
          <template #default="scope">
            {{ scope.row.periodStartingDate || '-' }} - {{ scope.row.periodEndDate || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleRemoveOrder(row)"> 移除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 可合并的其他订单列表 -->
    <div class="other-orders-list">
      <h3>可合并的其他订单</h3>
      <el-table
        :data="otherOrdersList"
        border
        style="width: 100%"
        v-loading="otherOrdersLoading"
        :empty-text="otherOrdersLoading ? '加载中...' : '暂无可合并的订单'"
      >
        <el-table-column label="商品名称" min-width="180">
          <template #default="{ row }">
            {{ row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.goodsPicture"
              :preview-src-list="[scope.row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="商品类型" min-width="120">
          <template #default="{ row }">
            {{ row.dealerGoodsTypeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100">
          <template #default="{ row }">
            {{ row.specifications || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="采购数量" min-width="80">
          <template #default="{ row }">
            {{ row.purchaseQuantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" min-width="80">
          <template #default="{ row }">
            {{ row.unit || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品产地" min-width="150">
          <template #default="{ row }">
            {{ row.address || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="商品有效期" min-width="200">
          <template #default="scope">
            {{ scope.row.periodStartingDate || '-' }} - {{ scope.row.periodEndDate || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleAddOrder(row)"> 添加 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer-actions">
      <div class="summary-info">
        <span v-if="mergedOrdersList.length > 0">已合并 {{ mergedOrdersList.length }} 个订单</span>
      </div>
      <el-button type="primary" @click="handlePostSendNow()">
        <template #icon>
          <LineMdSteering />
        </template>
        立即发货
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.delivery-note {
  overflow-y: auto;
  height: 80vh;
  .title {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}

.order-info,
.consignee-info,
.goods-list,
.merged-goods-list,
.other-orders-list {
  margin-top: 20px;
}

.footer-actions {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .summary-info {
    color: #409eff;
    font-weight: 500;
  }
}

.merged-goods-list {
  .el-table {
    border: 2px solid #67c23a;
  }

  h3 {
    color: #67c23a;
  }
}

.other-orders-list {
  .el-table {
    border: 2px solid #e6a23c;
  }

  h3 {
    color: #e6a23c;
  }
}
</style>
